package com.example.goband.api;

import com.example.goband.common.AppVariable;
import com.example.goband.model.User;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-05-31
 * Time: 19:30
 */

@Component
public class TestAPI extends TextWebSocketHandler {

    public TestAPI(){
        System.out.println("TestAPI load");
    }

    //客户端和服务器连接建立就绪会触发
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        WebSocketSession sb= session;
        User user = (User) session.getAttributes().get(AppVariable.USER_SESSION_KEY);
        System.out.println(user.getUserId()+"连接成功");
    }

    //客户端给服务器发了一个文本消息,可以感知到文本消息内容

    /**
     *
     * @param session
     * @param message 一个message对应一个websocket一个协议报文
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //getPayload()获取数据载荷
        System.out.println("Message:" + message.getPayload());

        //服务器收到消息以后原封不动返回回去
        session.sendMessage(message);
    }

    //出现问题时候会触发
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常");
    }

    //连接被关闭连接时候会执行
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭");
    }
}
